package com.iflytek.jzcpx.procuracy.ocr.entity.swx;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import lombok.Data;

@Data
/**
 * 二进制流文件包格式
 * 0字节 成功失败标识  bool
 * 1-8字节  数据区长度long
 * 9-99字节 code 内容 string
 * 100-299字节  params(包含请求参数) string
 * 300-499字节  message string
 * 500-结束  数据区长度 byte[]
 */
public class BinaryDataParam {
    boolean success;
    long dataLength;
    String code;
    String params;
    String message;
    byte[] data;

    public byte[] encode() {
        byte[] resultData = new byte[500 + data.length];
        resultData[0] = (byte) (success ? 1 : 0);
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(0, dataLength);
        byte[] dataLengthArray = buffer.array();
        System.arraycopy(dataLengthArray, 0, resultData, 1, 8);
        byte[] codeBytes = code.getBytes(StandardCharsets.UTF_8);
        System.arraycopy(codeBytes, 0, resultData, 9, codeBytes.length);
        byte[] paramsBytes = params.getBytes(StandardCharsets.UTF_8);
        System.arraycopy(paramsBytes, 0, resultData, 100, paramsBytes.length);
        byte[] msgBytes = message.getBytes(StandardCharsets.UTF_8);
        System.arraycopy(msgBytes, 0, resultData, 300, msgBytes.length);
        System.arraycopy(data, 0, resultData, 500, data.length);
        return resultData;
    }

    public void decode(byte[] inData) {
        success = inData[0] == 1;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.put(inData, 1, 8);
        buffer.flip();
        dataLength = buffer.getLong();
        code = new String(inData, 9, 90, StandardCharsets.UTF_8).trim();
        params = new String(inData, 100, 199, StandardCharsets.UTF_8).trim();
        message = new String(inData, 300, 199, StandardCharsets.UTF_8).trim();
        data = new byte[(int) dataLength];
        System.arraycopy(inData, 500, data, 0, (int) dataLength);
    }
}
